package Server;

import Data.ChatData;
import Data.GroupFriendData;
import Data.MassageData;
import Data.event;
import MyInterfaces.MassageType;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.sql.*;

public class InsertToGroup {
    String url = "jdbc:mysql://127.0.0.1:3306/nox?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8";
    String user = "root";
    String password = "Mi20030610.";

    private MassageData massageData;

    public InsertToGroup() {
    }

    public InsertToGroup(MassageData massageData) {
        this.massageData = massageData;
    }

    public boolean insert(ChatData chatData) throws SQLException, IOException {
        Connection Conn = DriverManager.getConnection(url, user, password);

        String id=chatData.getSender_id();
        String group_id= chatData.getReceiver_id();
        byte[] avatar=chatData.getSender_avatar();

        String sql="insert into group_identity_list (id,identity,group_id) values (?,0,?);";
        PreparedStatement operation=Conn.prepareStatement(sql);
        operation.setString(1,id);
        operation.setString(2,group_id);

        int k=operation.executeUpdate();
        if(k<=0) return false;
        //接下来需要给在线的管理员和群主显示一个消息
        //先从数据库查找
        String newsql="select *from group_identity_list where group_id=? and (identity=2 or identity=1);";
        operation=Conn.prepareStatement(newsql);
        operation.setString(1,group_id);
        ResultSet resultSet=operation.executeQuery();
        while(resultSet.next())
        {
            //需要得到对应的id
            String newid=resultSet.getString("id");
            if(ManageClientConnectionServerThread.existId(newid))
            {
                //如果这个人在线,给ta发送一个添加好友的一个信息
                Socket socket=ManageClientConnectionServerThread.getSocketByUserid(newid);
                event returnmassage=new event();
                GroupFriendData groupFriendData=new GroupFriendData();
                groupFriendData.setGroup_id(group_id);
                groupFriendData.setId(id);
                groupFriendData.setAvatar(avatar);
                groupFriendData.setIdentity(0);

                returnmassage.setType(MassageType.Add_Group_People);
                returnmassage.setT(groupFriendData);

                ObjectOutputStream writer=new ObjectOutputStream(socket.getOutputStream());
                writer.writeObject(returnmassage);
                writer.flush();
            }
        }
        return true;
    }
}
